import cv2
import mediapipe as mp
import time

import numpy as np

cap = cv2.VideoCapture(0)  # 调用摄像头
mpHands = mp.solutions.hands  # 调用手部模型
hands = mpHands.Hands()  # 使用默认的函式

# 设置样式
mpDraw = mp.solutions.drawing_utils
# 点的样式 red 粗度 5px
handLmsStyle = mpDraw.DrawingSpec(color=(0, 0, 255), thickness=5)
# 线的样式 green 粗度 5px
handConStyle = mpDraw.DrawingSpec(color=(0, 255, 0), thickness=5)
pTime = 0
cTime = 0
while True:
    #img = cv2.imread("1.webp")  # 查看摄像头读取的图像
    ret, img = cap.read()
    if ret:
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 将图片转为灰度图
        result = hands.process(imgRGB)  # 图片预测出来的一个结果
        # print(result.multi_hand_landmarks)
        imgHeight = img.shape[0]
        imgWidth = img.shape[1]

        if result.multi_hand_landmarks:
            posList = []
            for pos in result.multi_hand_landmarks[0].landmark:
                posList.append([pos.x*imgWidth, pos.y*imgHeight])
            print(posList[0])

            src = np.float32([posList[5], posList[17], posList[0]])
            dst = np.float32([[10, 10], [150, 10], [75, 200]])
            # 需要原始图片的三个点坐标, 和变换之后的三个对应的坐标
            M = cv2.getAffineTransform(src, dst)

            cut = cv2.warpAffine(img, M, (150, 150))
            ret = cv2.Canny(cut, 20, 50)
            cv2.imshow('cut', cut)

        cTime = time.time()
        fps = 1 / (cTime - pTime)  # 1秒/一张图片的显示时间=1秒显示多少帧
        pTime = cTime
        # 将fps输出到图片上
        cv2.putText(ret, f"FPS :{int(fps)}", (10, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

        #cv2.imshow('手', img)
        cv2.imshow('test', ret)

    if cv2.waitKey(1) == ord('q'):
        break

